﻿using System;
using System.Web.Security;
using Jayden.Dll.Core.Enums;
using Jayden.Dll.Core.Membership;
using Jayden.Dll.Web.Events;
using Jayden.Dll.Web.Helper;
using Jayden.Dll.Web.HtmlControls;

namespace Jayden.Dll.Web.Controls.Authenticated
{
	public class UserForm : Form
	{
		public delegate void OnUpdateUserSuccess(HttpHandlerContext context, User user);
		public delegate void OnUpdateUserFailed(HttpHandlerContext context);

		public class UpdateUserCommandHandler : HttpCommandHandler
		{
			public UpdateUserCommandHandler() : this("UpdateUser", "ValidateEmail") { }
			public UpdateUserCommandHandler(string updateUserCommand, string validateEmailCommand)
				: base(updateUserCommand, validateEmailCommand)
			{
				RegisterEvent("UpdateUserFailed");
				RegisterEvent("UpdateUserSuccess");
			}
			public event OnUpdateUserFailed UpdateUserFailed { add { AddEvent<OnUpdateUserFailed>("UpdateUserFailed", value); } remove { RemoveEvent<OnUpdateUserFailed>("UpdateUserFailed", value); } }
			public event OnUpdateUserSuccess UpdateUserSuccess { add { AddEvent<OnUpdateUserSuccess>("UpdateUserSuccess", value); } remove { RemoveEvent<OnUpdateUserSuccess>("UpdateUserSuccess", value); } }

			protected override void ProcessCommand(HttpHandlerContext context, string command)
			{
				if (command == "UpdateUser")
				{
					string username = context.Context.Request["username"];
					string password = context.Context.Request["password"];
					string lastName = context.Context.Request["lastName"];
					string firstName = context.Context.Request["firstName"];
					string passwordQuestion = context.Context.Request["passwordQuestion"];
					string passwordAnswer = context.Context.Request["passwordAnswer"];
					string gender = context.Context.Request["gender"];
					string birthDate = context.Context.Request["birthDate"];

					User user = Membership.GetUser(username) as User;

					if (user != null && user.Password == password)
					{
						user.FirstName = firstName;
						user.LastName = lastName;
						user.PasswordQuestion = passwordQuestion;
						user.PasswordAnswer = passwordAnswer;
						user.Gender = (Gender)Enum.Parse(typeof(Gender), gender, true);
						user.BirthDate = HtmlHelper.FromHtmlDate(birthDate, DateTime.MinValue);
						Membership.UpdateUser(user);
						Invoke("UpdateUserSuccess", context, user);
					}
					else
						Invoke("UpdateUserFailed", context);
				}
				else if (command == "ValidateEmail")
				{
					User user = Membership.GetUser() as User;
					if (user != null && !user.IsEmailValidated)
					{
						Uri uri = new Uri(context.Request.Url, "/register.html", false);
						user.Guid = Guid.NewGuid().ToString("N");
						Membership.UpdateUser(user);
						RegisterForm.RegisterCommandHandler.SendEmailValidation(uri, context.GetMailer(null), user);
						//add event 
					}
				}
			}
		}

		private Input m_Username;
		private Input m_Password;
		private Input m_Email;
		private Input m_LastName;
		private Input m_FirstName;
		private Input m_PasswordQuestion;
		private Input m_PasswordAnswer;
		private Select m_Gender;
		private Input m_BirthDate;
		private Img m_EmailStatus;
		private A m_ValidateEmail;

		private Button m_Update;

		public override void Load(System.Xml.XmlNode node, HtmlControlLoader loader)
		{
			base.Load(node, loader);

			if (Id == null)
				Id = "registerForm";
			m_Username = GetFormElement<Input>("username");
			m_Password = GetFormElement<Input>("password");
			m_Email = GetFormElement<Input>("email");
			m_LastName = GetFormElement<Input>("lastName");
			m_FirstName = GetFormElement<Input>("firstName");
			m_Gender = GetFormElement<Select>("gender");
			m_BirthDate = GetFormElement<Input>("birthDate");
			m_PasswordQuestion = GetFormElement<Input>("passwordQuestion");
			m_PasswordAnswer = GetFormElement<Input>("passwordAnswer");
			m_Update = GetFormElement<Button>("update", "command");
			m_EmailStatus = GetElementByServerId<Img>("emailStatus");
			m_ValidateEmail = GetElementByServerId<A>("validateEmail");
		}

		private void LoadFromContext(HttpHandlerContext context)
		{
			User user = context.User;

			if (user != null)
			{
				m_Username.Value = user.UserName;
				m_Email.Value = user.Email;
				m_FirstName.Value = user.FirstName;
				m_LastName.Value = user.LastName;
				m_BirthDate.Value = HtmlHelper.ToHtmlDate(user.BirthDate);
				m_Gender.SelectedValue = user.Gender.ToString();
				m_PasswordQuestion.Value = user.PasswordQuestion;
				m_PasswordAnswer.Value = user.PasswordAnswer;

				if (user.IsEmailValidated)
				{
					m_ValidateEmail.ServerRender = false;
					m_EmailStatus.Src = "/Images/Icons/mail-validated.png";
					m_EmailStatus.Title = "Your email has been validated.";
				}
				else {
					m_EmailStatus.Src = "/Images/Icons/mail-not-validated.png";
					m_EmailStatus.Title = "Your email has NOT been validated.";
				}
			}
		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			base.ProcessHtmlRequest(context);
			LoadFromContext(context);
			UpdateUserCommandHandler handler = context.HandlerManager.GetHandler<UpdateUserCommandHandler>();
		}

		public override void ProcessJsonRequest(HttpHandlerContext context)
		{
			base.ProcessJsonRequest(context);
			LoadFromContext(context);
			UpdateUserCommandHandler handler = context.HandlerManager.GetHandler<UpdateUserCommandHandler>();
		}

		public override void ProcessJsRequest(HttpHandlerContext context)
		{
			base.ProcessJsRequest(context);
			string id = Id;
			context.Js[id].AppendAjaxSubmit(this, m_Update);
		}

	}
}
